package com.cas.controller;

import com.cas.utils.CustomConstants;
import org.apache.commons.lang.StringUtils;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.apereo.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录校验码
 * @author Leighton
 * @create 2018-11-15.
 */
public class ValidateLoginCaptchaAction extends AbstractAction{
    private static final Logger LOGGER = LoggerFactory.getLogger(ValidateLoginCaptchaAction.class);
    private static final String CODE = "captchaError";
    /**
     * 前端验证码
     */
    public static final String CODE_PARAM = "captcha";
    @Override
    protected Event doExecute(RequestContext context) throws Exception {
        Credential credential = WebUtils.getCredential(context);
//        自定义属性 WebUtils
//        context.getFlowScope().put("captchaAuthenticationEnabled",true);
        //
        if (credential instanceof UsernamePasswordCredential){
            if (isEnable()){
                LOGGER.info("开始校验登录校验码");
                //WebUtils.getHttpServletRequest();
                HttpServletRequest request =WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
                HttpSession httpSession = request.getSession();
                //校验码
                String inCode = request.getParameter(CODE_PARAM);
              Object attribute= httpSession.getAttribute("captcha");
                String realCaptcha = attribute == null ? null : attribute.toString();
                //校验码失败跳转到登录页
                if(StringUtils.isBlank(inCode) || !inCode.toUpperCase().equals(realCaptcha)){
                    return getError(context);
                }
            }
        }
        return null;
    }
    /**
     * 是否开启验证码
     * @return
     */
    private boolean isEnable() {
        return false;
    }


    private void configureWebflowContext(final RequestContext context){
        context.getFlashScope().put(CustomConstants.CAPTCHA_AUTHENTICATION_ENABLED,true);
    }
    /**
     * 跳转到错误页
     * @param requestContext
     * @return
     */
    private Event getError(final RequestContext requestContext) {
        final MessageContext messageContext = requestContext.getMessageContext();
        messageContext.addMessage(new MessageBuilder().error().code(CODE).build());
        return getEventFactorySupport().event(this, CODE);
    }

}
